<?php

namespace system\model;

use houdunwang\model\Model;
use houdunwang\session\Session;
use houdunwang\validate\Validate;

class Admin extends model
{
    //操作的数据表
    protected $table = "admin";

    //登录
    public function login()
    {
        //1.验证数据不能为空
        $data = [
            'admin_username'=>q('post.admin_username'),
            'admin_password'=>q('post.admin_password'),
            'code'=>q('post.code'),
        ];
        //p($data);die;
        $res = Validate::make( [
            [ 'admin_username', 'isnull', '请输入用户名', 3 ],
            [ 'admin_password', 'isnull', '请输入密码', 3 ],
            [ 'code', 'isnull', '请输入验证码', 3 ],
        ] ,$data);
        //2.比对用户名密码是否正确
        $userInfo = $this->where('admin_username',$data['admin_username'])->first();
        if(!$userInfo){
            return ['valid'=>0,'msg'=>'用户名不正确'];
        }
        //校验密码
        if(!password_verify($data['admin_password'],$userInfo['admin_password']))
        {
            return ['valid'=>0,'msg'=>'用户密码不正确'];
        }


//			$userInfo = $this->where('admin_username',$data['admin_username'])
//				->where('admin_password',password_hash($data['admin_password'],PASSWORD_DEFAULT))
//				->first();
//			if(!$userInfo){
//				return ['valid'=>0,'msg'=>'用户名或者密码不正确'];
//			}
        //3.比对验证码是否正确
        //var_dump(Code::auth( 'code' ));die;
        if(!Code::auth( 'code' ))
        {
            return ['valid'=>0,'msg'=>'验证码不正确'];
        }
        //4.将当前登录用户信息存入session
        Session::set('admin.admin_id',$userInfo['admin_id']);
        Session::set('admin.admin_username',$userInfo['admin_username']);
        //5.返回成功
        return ['valid'=>1,'msg'=>'登录成功'];
    }

//    修改密码
public  function  changePassword($data){
//    p($data);

//    自动验证
    Validate::make([
        ['admin_password','required','请输入旧密码',Validate::MUST_VALIDATE],
        ['newPassword','required','请输入新密码',Validate::MUST_VALIDATE],
        ['retryPassword','confirm:newPassword','请确认新密码',Validate::MUST_VALIDATE],
    ]);
//    取出数据验证旧密码是否正确
    $userInfo = self::find(Session::get('admin.admin_id'));

//    p($userInfo['admin_password']);




    if(!password_verify($data['admin_password'] ,$userInfo['admin_password'])){
        return ['valid'=>0,'message'=>'原始密码不正确'];
    }
    $userInfo->admin_password = password_hash($data['newPassword'],PASSWORD_DEFAULT);
    $userInfo->save();
    return ['valid'=>1,'message'=>'修改成功'];
}
}